/**
 * Created by mooshroom on 2015/6/21 0021.
 *
 * 文章详情模块
 */
define('art', [
    'avalon',
    '../../ui/MDEditor/prettify.js',
    'css!../../ui/MDEditor/MDEditor.css',
    'css!../../package/art/art.css',
    '../../ui/MDEditor/markdown'
], function () {
    return art = avalon.define({
        $id: "art",
        ready: function (id) {
            art.Get(id)

            avalon.scan()

            setTimeout(function(){
                if(art.replyTotal==0){
                    art.gettingMore=true
                }
            },1)
        },
        thisUID: cache.go('uid'),
        //获取文章
        info: {
            Title: '正在加载……'

        },
        Get: function (id) {

            $.call({
                type: "post",
                i: "GetArticle",
                data: {
                    ArticleID: id
                },
                success: function (res) {
                    if (res.c == 200) {
                        art.info = res.d
                        setTimeout(function () {
                            prettyPrint();
                        }, 200)
                        art.getReply()
                    }
                }
            })

        },
        del: function () {
            if (window.confirm("╥﹏╥...真的要抹消我的存在么？o(TヘTo)不要啊~~~")) {
                $.call({
                    type: "post",
                    i: "DelArticle",
                    data: {
                        ArticleID: art.info.ArticleID
                    },
                    success: function (res) {
                        if (res.c == 200) {
                            tip.on("删除成功", 1, 3000)
                            history.go(-1)
                        }
                    }
                })
            }
        },


        /*评论列表抓取*/
        replyList: [],
        replyPage: 1,
        replyTotal: 0,
        getReply: function () {
            $.call({
                i: "CMS_Comment",
                type: "post",
                data: {
                    ArticleID: art.info.ArticleID,
                    Page: art.replyPage,
                    PageNumber: 16
                },
                success: function (res) {
                    if (res.c == 200) {
                        //获取成功
                        var l = res.d.List;
                        if (res.d.List.length > 0) {
                            //有数据


                            art.replyPage = res.d.Page
                            art.replyTotal = res.d.Total
                            for (var i = 0; i < l.length; i++) {
                                //编译MD格式
                                l[i].ContentHtml = marked(l[i].Content)

                                art.replyList.push(l[i])
                            }

                            art.buildQoute()

                            //判断还有没有更多
                            if (art.replyTotal == art.replyList.length) {
                                //已经没有更多了
                                art.gettingMore = true
                            }
                            else {
                                art.gettingMore = false
                            }

                        }
                        else {
                            //没有数据了
                            tip.on("没有更能多评论了", 1, 3000)
                        }

                    }
                    else {
                        tip.on(res.m)
                    }
                }
            })
        },
        gettingMore: false,
        moreReply: function () {
            //获取更多的评论
            art.gettingMore = true
            art.replyPage++
            art.getReply()
        },


        /*回复功能区域 */
        editing: false,
        editorInit: function (index) {

            if (door.logined == true) {

                //滚动到回复按钮的高度
                function getTop(e){
                    var offset=e.offsetTop;
                    if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
                    return offset;
                }
                var top=0
                top=getTop(document.getElementById("btnReply"))

                if(document.documentElement&&document.documentElement.scrollTop){
                    document.documentElement.scrollTop=top
                }
                else if(document.body){
                    document.body.scrollTop=top
                }


                //加载编辑器
                require(['../../ui/MDEditor/MDEditor'], function () {
                    avalon.scan()
                    art.editing = true
                    replyEditor.md = ""

                    // 如果是回复他人的评论，则抓取所需要评论的额内容到编辑器内部，当然，在这之前需要验证编辑器是否准备好，如果没有则等一下在执行
                    if (index >= 0) {
                        //判断为回复

                        //抓取内容
                        var theComment = art.replyList[index];
                        var theMan = theComment.CommentUser.UserName,
                            theWords = theComment.Content;

                        //剔除回复内容里面的回复内容（去掉嵌套内容）
                        var innerReply = /```(.*\n)*```/g
                        var matches = innerReply.exec(theWords)

                        console.log(matches)
                        theWords = theWords.replace(innerReply, '')

                        //生成字符串
                        var quote = "```reply\n" + theWords + "\n" + "@" + theMan + "\n```\n\n";

                        //填入MD
                        function replaceContent() {
                            if (replyEditor.md != undefined) {
                                //编辑器准备好了
                                replyEditor.md = quote

                            }
                            else {
                                setTimeout(function () {
                                    replaceContent()
                                }, 400)
                            }

                        }

                        replaceContent()

                    }

                })
            }
            else {
                tip.on("您还没有登录或登录已失效，请先登录后在评论")
            }


        },
        //回复编辑器的配置
        replyOpt: {
            height: 400,
            loadLocaDoc: false,
            initType: 0
        },
        reply: function () {
            //提交评论
            $.call({
                i: "CMS_Comment",
                type: "post",
                data: {
                    ArticleID: art.info.ArticleID,
                    Content: replyEditor.md
                },
                success: function (res) {
                    if (res.c == 200) {
//                        评论成功
                        tip.on("评论成功", 1, 3000)
                        art.editing = false

                        //todo 将这条评论插入到评论列表中
                        var newReply = {
                            CommentUser: {
                                UserName: cache.go("un"),
                                UID: cache.go("uid")
                            },
                            Time: new Date() / 1000,
                            ContentHtml: marked(replyEditor.md),
                            Content: replyEditor.md
                        };
                        art.replyList.push(newReply)
                        art.replyTotal++
                        art.buildQoute()

                    }
                    else {
                        tip.on(res.m)
                    }
                }
            })
        },

        //组织回复引用块的样式
        buildQoute: function () {
            var l = document.getElementsByClassName("lang-reply")
            var lold = document.getElementsByClassName("lang-回复")

            //依次处理每个评论
            doIt(l);
            l = [];
            doIt(lold)
            lold = []

            function doIt(l) {
                var err = false
                for (var i = 0; i < l.length; i++) {


                    var spans = l[i].getElementsByTagName("span")
                    console.log(spans)
                    var str = ""
                    var enough = false
                    if (spans.length == 0) {
                        err = true
                        console.log("这个框框里面没有spans")
                        str = l[i].innerText
                    }
                    else {
                        err = false
                        //查询span标签内的文字，提取到str上面
                        for (var o = 0; o < spans.length; o++) {
                            //预览字符串长度在这里设置
                            if (str.length >= 30) {
                                enough = true
                            }
                            if (enough && spans[o].innerText == ("\n" | "" | "\r\n" | "\n\n" | "\r\n\r\n")) {
                                //是时候跳出了
                                str = str + "\n......（这里省略很多个字）\n\n" + spans[spans.length - 1].innerText
                                break
                            }
                            else {
                                str = str + spans[o].innerText
                            }


                            console.log(str)


                        }
                    }


                    l[i].style.display = "none"

                    var box = document.createElement("div")
                    box.innerHTML = marked(str)
                    var p = l[i].parentElement || l[i].parentNode || null
                    p.appendChild(box)
                    p.setAttribute("class", "reply-qoute")


                }

                var len = l.length
                for (var q = 0; q < len; q++) {
                    l[0].setAttribute("class", "")
                }
                prettyPrint()


            }


        }



    })
})